package com.ppm.project.manuscripts.service.impl;

import java.io.FileNotFoundException;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ppm.common.utils.DateUtils;
import com.ppm.common.utils.file.WebFileUtils;
import com.ppm.project.api.domain.Manuscripts;
import com.ppm.project.manuscripts.domain.ShareManuscripts;
import com.ppm.project.manuscripts.mapper.ShareManuscriptsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ppm.project.manuscripts.mapper.PpmSourceMaterialMapper;
import com.ppm.project.manuscripts.domain.PpmSourceMaterial;
import com.ppm.project.manuscripts.service.IPpmSourceMaterialService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 共享素材管理Service业务层处理
 * 
 * @author ppm
 * @date 2020-08-11
 */
@Service
public class PpmSourceMaterialServiceImpl extends ServiceImpl<PpmSourceMaterialMapper,PpmSourceMaterial> implements IPpmSourceMaterialService
{
    public Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PpmSourceMaterialMapper ppmSourceMaterialMapper;
    @Autowired
    private ShareManuscriptsMapper shareManuscriptsMapper;

    /**
     * 查询共享素材管理
     * 
     * @param id 共享素材管理ID
     * @return 共享素材管理
     */
    @Override
    public PpmSourceMaterial selectPpmSourceMaterialById(Long id)
    {
        return ppmSourceMaterialMapper.selectPpmSourceMaterialById(id);
    }

    /**
     * 查询共享素材管理列表
     * 
     * @param ppmSourceMaterial 共享素材管理
     * @return 共享素材管理
     */
    @Override
    public List<PpmSourceMaterial> selectPpmSourceMaterialList(PpmSourceMaterial ppmSourceMaterial)
    {
        return ppmSourceMaterialMapper.selectPpmSourceMaterialList(ppmSourceMaterial);
    }

    /**
     * 新增共享素材管理
     * 
     * @param ppmSourceMaterial 共享素材管理
     * @return 结果
     */
    @Override
    public int insertPpmSourceMaterial(PpmSourceMaterial ppmSourceMaterial)
    {
        ppmSourceMaterial.setCreateTime(DateUtils.getNowDate());
        return ppmSourceMaterialMapper.insertPpmSourceMaterial(ppmSourceMaterial);
    }

    /**
     * 修改共享素材管理
     * 
     * @param ppmSourceMaterial 共享素材管理
     * @return 结果
     */
    @Override
    public int updatePpmSourceMaterial(PpmSourceMaterial ppmSourceMaterial)
    {
        ppmSourceMaterial.setUpdateTime(DateUtils.getNowDate());
        return ppmSourceMaterialMapper.updatePpmSourceMaterial(ppmSourceMaterial);
    }

    /**
     * 批量删除共享素材管理
     * 
     * @param ids 需要删除的共享素材管理ID
     * @return 结果
     */
    @Override
    public int deletePpmSourceMaterialByIds(Long[] ids)
    {
        return ppmSourceMaterialMapper.deletePpmSourceMaterialByIds(ids);
    }

    /**
     * 删除共享素材管理信息
     * 
     * @param id 共享素材管理ID
     * @return 结果
     */
    @Override
    public int deletePpmSourceMaterialById(Long id)
    {
        return ppmSourceMaterialMapper.deletePpmSourceMaterialById(id);
    }


    /**
     * 解析h5中的资源,并保存到数据库
     * @param manuscripts
     * @param siteUrl
     */
    @Override
    @Transactional
    public void getAndSaveH5MaterialUrl(List<Manuscripts> manuscripts, String siteUrl) {

        for(Manuscripts manuscript : manuscripts){

            String h5Html = manuscript.getH5Html();
            getAndSaveMaterial(h5Html, siteUrl, manuscript.getArticleId());


        }
    }

    @Override
    @Transactional
    public boolean syncMaterial(String articleId) {

        List<Map<String, String>> result = this.shareManuscriptsMapper.selectMapByArticleId(articleId);
        if(result!= null && result.size()>0){

            String siteUrl = result.get(0).get("site_url");
            String h5Html = result.get(0).get("h5_html");
            getAndSaveMaterial(h5Html, siteUrl, articleId);

        }
        return true;
    }


    public void getAndSaveMaterial(String h5Html, String siteUrl,String articleId){
        List<PpmSourceMaterial> ppmSourceMaterialList = new ArrayList<>();
        String resourceUrl =(siteUrl.endsWith("/")?siteUrl.substring(0, siteUrl.length()-1):siteUrl)+h5Html;
        try {
            Map<String, Set<String>> m = WebFileUtils.getMaterialFileUrlMap(resourceUrl);
            Set<String> imageSrcSet = m.get("img");
            Set<String> videoSrcSet = m.get("video");
            Set<String> audioSrcSet = m.get("audio");
            if(imageSrcSet != null && imageSrcSet.size() >0){
                for (String imageUrl : imageSrcSet){
                    PpmSourceMaterial material =
                            buildPpmSourceMaterial(imageUrl, siteUrl,
                                    articleId, "img");
                    ppmSourceMaterialList.add(material);
                }
            }

            if(videoSrcSet != null && videoSrcSet.size() >0){
                for (String videoUrl : videoSrcSet){
                    PpmSourceMaterial material =
                            buildPpmSourceMaterial(videoUrl, siteUrl,
                                    articleId, "video");
                    ppmSourceMaterialList.add(material);
                }
            }

            if(audioSrcSet != null && audioSrcSet.size() >0){
                for (String audioUrl : audioSrcSet){
                    PpmSourceMaterial material =
                            buildPpmSourceMaterial(audioUrl, siteUrl,
                                    articleId, "audio");
                    ppmSourceMaterialList.add(material);
                }
            }
            HashMap map = new HashMap();
            map.put("article_id", articleId);
            this.removeByMap(map);
            if(ppmSourceMaterialList.size()>0){

                //保存资源文件信息
                this.saveOrUpdateBatch(ppmSourceMaterialList);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            if(e.getCause()!=null && e.getCause() instanceof FileNotFoundException){
                throw new RuntimeException("未找到资源文件:"+e.getCause().getMessage());
            }else{

                throw new RuntimeException(e);
            }
        }

    }

    public PpmSourceMaterial buildPpmSourceMaterial(String srcUrl,String siteUrl, String articleId, String type){
        PpmSourceMaterial material = new PpmSourceMaterial();
        material.setArticleId(articleId);
        material.setType(type);
        if(srcUrl.startsWith("/sctv"))
            material.setMaterialUrl((siteUrl.endsWith("/")?siteUrl.substring(0, siteUrl.length()-1):siteUrl)+srcUrl);
        else
            material.setMaterialUrl(srcUrl);
        material.setMaterialName(WebFileUtils.getFileName(srcUrl));
        material.setCreateTime(DateUtils.getNowDate());

        return material;
    }

}
